package com.employmentapp;

import android.util.Log;

import com.employmentapp.entity.ResponseInfo;
import com.employmentapp.entity.UserInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求
 */
public class ApiManager {

    private static final String TAG = "ApiManager";
    private static final ApiManager INSTANCE = new ApiManager();
    private OkHttpClient mOkHttpClient;
    private final Executor mThreadPools = Executors.newCachedThreadPool();

    private ApiManager() {
        mOkHttpClient = new OkHttpClient();
    }

    public static ApiManager getInstance() {
        return INSTANCE;
    }

    public Executor getThreadPools() {
        return mThreadPools;
    }

    public ResponseInfo<UserInfo> login(String username, String password) {
        try {
            final String url = "http://192.168.31.12:9080/user/getAdminByName?username=" + username
                    + "&password=" + password;
            /*
            final RequestBody body = new FormBody.Builder()
                    .add("username", username)
                    .add("password", password)
                    .build();
             */
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            final Response response = mOkHttpClient.newCall(request).execute();
            final String json = response.body().string();
            Log.i(TAG, "login json:" + json);
            final Gson gson = new Gson();
            final ResponseInfo<UserInfo> responseInfo = gson.fromJson(json, new TypeToken<ResponseInfo<UserInfo>>() {
            }.getType());
            Log.i(TAG, "login, responseInfo:" + responseInfo);
            return responseInfo;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

}
